/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: AddressListActivity.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.account.ui;

import android.content.Intent;
import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.List;

import io.bhex.app.R;
import io.bhex.sdk.trade.bean.AddressListResponse;
import io.bhex.sdk.trade.bean.TwoVerifyBean;
import io.bhex.sdk.account.bean.UserInfoBean;
import io.bhex.app.account.presenter.AddressListPresenter;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.utils.VerifyUtil;
import io.bhex.baselib.constant.AppData;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.DialogUtils;
import io.bhex.app.utils.IntentUtils;
import io.bhex.baselib.core.SPEx;
import io.bhex.sdk.account.UserInfo;
import io.bhex.app.view.TopBar;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.baselib.view.alertview.AlertView;
import io.bhex.baselib.view.alertview.OnDismissListener;

/**
 * ================================================
 * 描   述：币地址列表
 * ================================================
 */

public class AddressListActivity extends BaseActivity<AddressListPresenter,AddressListPresenter.AddressListUI> implements AddressListPresenter.AddressListUI, View.OnClickListener, SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {
    private static final int REQUEST_CODE_OF_ADDRESS = 0x005;
    private TopBar topBar;
    private RecyclerView recyclerView;
    private AddressListAdapter adapter;
    private SwipeRefreshLayout swipeRefresh;
    private View emptyView;
    private UserInfoBean userInfo;
    private String mobile;
    private boolean bindGA;
    private String email;
    private boolean isBindMobile=false;
    private boolean isBindEmail=false;
    //默认验证邮箱
    private boolean isVerifyEmail=true;
    private AddressListResponse.AddressBean deleteAddressBean;
    private String tokenId="";
    private String tokenName="";
    private String tokenFullName="";
    private String iconUrl="";
    private String from="";
    private Boolean isEOS = false;
    private AlertView alertView;
    private String chainType="";

    @Override
    protected int getContentView() {
        return R.layout.activity_quota_token_list_activity;
    }

    @Override
    protected AddressListPresenter createPresenter() {
        return new AddressListPresenter();
    }

    @Override
    protected AddressListPresenter.AddressListUI getUI() {
        return this;
    }

    @Override
    protected boolean isNeedLogin() {
        return true;
    }

    @Override
    protected void initView() {
        super.initView();
        topBar = viewFinder.find(R.id.topBar);
        topBar.setLeftImg(R.mipmap.btn_head_back);
        topBar.setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        topBar.setRightImg(CommonUtil.isBlackMode()?R.mipmap.icon_add_night:R.mipmap.icon_add);
        topBar.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(tokenId)) {
                    IntentUtils.goAddCoinAddress(AddressListActivity.this,chainType,tokenId,tokenName,tokenFullName,iconUrl,isEOS);
                }
            }
        });

        userInfo = UserInfo.getUserInfo();
        if (userInfo != null) {
            bindGA = userInfo.isBindGA();
            mobile = userInfo.getMobile();
            email = userInfo.getEmail();
            isBindMobile = !TextUtils.isEmpty(mobile)&&userInfo.getRegisterType()!=1;
            isBindEmail = !TextUtils.isEmpty(email)&&userInfo.getRegisterType()!=2;

            /**
             * 验证的是与登录模式相反的 eg.邮箱登录二次验证手机，手机登录二次验证邮箱
             */
            isVerifyEmail = !SPEx.get(AppData.SPKEY.USER_ACCOUNT_MODE_KEY,true);
        }

        Intent intent = getIntent();
        if (intent != null) {
            tokenId = intent.getStringExtra("tokenId");
            tokenName = intent.getStringExtra("tokenName");
            chainType = intent.getStringExtra("chainType");
            tokenFullName = intent.getStringExtra("tokenFullName");
            isEOS = intent.getBooleanExtra("isEOS", false);
            iconUrl = intent.getStringExtra("icon");
            from = intent.getStringExtra("from");
            topBar.setTitle(getString(R.string.string_title_address_manage_format,tokenName));

        }

        swipeRefresh = viewFinder.find(R.id.swipeRefresh);
        swipeRefresh.setEnabled(false);
        recyclerView = viewFinder.find(R.id.recyclerView);
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        emptyView = layoutInflater.inflate(R.layout.empty_layout, swipeRefresh, false);
        ViewGroup.LayoutParams layoutParams = emptyView.getLayoutParams();
        layoutParams.height = PixelUtils.dp2px(300);
        emptyView.setLayoutParams(layoutParams);
        emptyView.findViewById(R.id.empty_txt).setOnClickListener(this);
        emptyView.findViewById(R.id.empty_img).setOnClickListener(this);

    }

    @Override
    protected void addEvent() {
        super.addEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(tokenId) && UserInfo.isLogin()) {
            getPresenter().getAddressListByToken(tokenId,chainType);
        }
    }

    @Override
    public String getChainType() {
        return chainType;
    }

    @Override
    public void showAddressList(List<AddressListResponse.AddressBean> datas) {
        if (adapter == null) {
            adapter = new AddressListAdapter(datas);
//            adapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
            adapter.isFirstOnly(false);
//            adapter.setOnLoadMoreListener(this);
            swipeRefresh.setColorSchemeColors(Color.RED, Color.BLUE, Color.GREEN);
            swipeRefresh.setOnRefreshListener(this);
            swipeRefresh.setEnabled(false);

            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            recyclerView.setItemAnimator(new DefaultItemAnimator());
//            DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL);
//            RecycleViewDivider dividerItemDecoration = new RecycleViewDivider(getContext(), LinearLayoutManager.HORIZONTAL, 2, SPEx.get(AppData.SPKEY.SKIN_IS_BLACK_MODE,false)?getResources().getColor(R.color.divider_line_color_night):getResources().getColor(R.color.divider_line_color), PixelUtils.dp2px(10), PixelUtils.dp2px(10));
//            dividerItemDecoration.setDrawable(ContextCompat.getDrawable(getActivity(),R.drawable.divider));
//            recyclerView.addItemDecoration(dividerItemDecoration);
            recyclerView.setAdapter(adapter);
//            adapter.setEmptyView(true, true, emptyView);
            adapter.setEmptyView(emptyView);
        } else {
            adapter.setNewData(datas);
        }
    }

    @Override
    public void requestUserInfoSuccess(UserInfoBean data) {
        if (userInfo != null) {
            VerifyUtil.is2FA(this, userInfo, new VerifyUtil.VerifyListener() {
                @Override
                public void on2FAVerify(boolean isVerify2FA) {
                    if (!isVerify2FA) {
                        //没有二次绑定认证
                        return;
                    }else{
                        bindGA = userInfo.isBindGA();
                        mobile = userInfo.getMobile();
                        email = userInfo.getEmail();
                        isBindMobile = !TextUtils.isEmpty(mobile)&&userInfo.getRegisterType()!=1;
                        isBindEmail = !TextUtils.isEmpty(email)&&userInfo.getRegisterType()!=2;

                        DialogUtils.showDialog(AddressListActivity.this, "", getString(R.string.string_are_you_sure_delete_address), getString(R.string.string_sure), getString(R.string.string_cancel), true, new DialogUtils.OnButtonEventListener() {
                            @Override
                            public void onConfirm() {
                                IntentUtils.goTwoVerify(AddressListActivity.this, REQUEST_CODE_OF_ADDRESS, "from_address_delete", "", "9", bindGA, isBindMobile, isBindEmail, isVerifyEmail);
                            }

                            @Override
                            public void onCancel() {

                            }
                        });
                    }
                }
            });
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK){
            if (alertView!=null&&alertView.isShowing()) {
                alertView.dismiss();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onLoadMoreRequested() {
        swipeRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                adapter.loadMoreComplete();
            }
        }, 500);
    }

    @Override
    public void onRefresh() {
        setRefreshing(false);
    }


    public void setRefreshing(final boolean refreshing) {
        swipeRefresh.post(new Runnable() {
            @Override
            public void run() {
                swipeRefresh.setRefreshing(refreshing);
            }
        });
    }

    private class AddressListAdapter extends BaseQuickAdapter<AddressListResponse.AddressBean,BaseViewHolder> {

        AddressListAdapter(List<AddressListResponse.AddressBean> data) {
            super(R.layout.item_address_layout, data);
        }

        @Override
        protected void convert(final BaseViewHolder baseViewHolder, final AddressListResponse.AddressBean itemModel) {
            baseViewHolder.setVisible(R.id.item_divider, baseViewHolder.getAdapterPosition() != mData.size());
            baseViewHolder.setText(R.id.token_remark_name,itemModel.getRemark());
            baseViewHolder.setText(R.id.token_address,itemModel.getAddress());
            baseViewHolder.setText(R.id.chain_type,itemModel.getChainType());
            if(isEOS == true) {
                baseViewHolder.getView(R.id.token_address_tag).setVisibility(View.VISIBLE);
                baseViewHolder.setText(R.id.token_address_tag, itemModel.getAddressExt());
            }
            else
                baseViewHolder.getView(R.id.token_address_tag).setVisibility(View.GONE);

            baseViewHolder.getConvertView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (from.equals("manage")) {
                        //来自地址管理
                        alertView = new AlertView(null, null, getString(R.string.string_cancel), null, new String[]{getResources().getString(R.string.string_copy_address),getResources().getString(R.string.string_delete_address)}, AddressListActivity.this, AlertView.Style.ActionSheet, new io.bhex.baselib.view.alertview.OnItemClickListener() {
                            @Override
                            public void onItemClick(Object o, int position) {
                                if (position == -1) {
                                    return;
                                }
                                if (position == 0) {
                                    //切换到:复制
                                    CommonUtil.copyText(AddressListActivity.this,itemModel.getAddress());
                                } else {
                                    //切换到:删除
                                    deleteAddressBean = itemModel;
//                                    getPresenter().getUserInfo();
                                    //删除地址去除2FA校验
                                    getPresenter().deleteAddress(deleteAddressBean);
                                }
                            }
                        });

                        alertView.setOnDismissListener(new OnDismissListener() {
                            @Override
                            public void onDismiss(Object o) {

                            }
                        });
                        alertView.show();

                    }else{
                        //来自选择地址
                        Intent intent = new Intent();
                        intent.putExtra("address",itemModel);
                        setResult(RESULT_OK,intent);
                        finish();
                    }
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_CODE_OF_ADDRESS && resultCode == RESULT_OK){
            if (data != null) {
                TwoVerifyBean twoVerifyBean = (TwoVerifyBean)data.getSerializableExtra("twoVerify");
                //去删除提币地址
                if (deleteAddressBean != null&&twoVerifyBean!=null) {
                    getPresenter().deleteAddress(deleteAddressBean,twoVerifyBean);
                }else{
                    ToastUtils.showShort(this,getString(R.string.string_wait_retry));
                }
            }
        }
    }
}
